﻿using System;

namespace UnionnetClient.Model
{
	public class UnconfigState : StateBase
	{
		public UnconfigState(StateMachine stateMachine) : base(stateMachine)
		{
			if (!AppEnvironment.Settings.IsLoginSourceCorrect)
			{
				lsg = new LoginSourceGetter();
				lsg.GetLoginSourceCompleted += lsg_GetLoginSourceCompleted;
				lsg.GetLoginSourceAsync();
			}
		}

		public event EventHandler GetLoginSourceCompleted;

		internal override void SetAccount(string username, string password)
		{
			base.SetAccount(username, password);

			if (AppEnvironment.Settings.IsLoginSourceCorrect)
			{
				stateMachine.SetState(stateMachine.UnloginS);
			}
		}

		protected virtual void OnGetLoginSourceCompleted()
		{
			if (GetLoginSourceCompleted != null)
			{
				GetLoginSourceCompleted(this, EventArgs.Empty);
			}
		}

		private LoginSourceGetter lsg;

		private void lsg_GetLoginSourceCompleted(object sender, GetLoginSourceCompletedEventArgs e)
		{
			if (e.Successful)
			{
				AppEnvironment.Settings[SettingsProperty.LoginSource] = e.Source;

				if (AppEnvironment.Settings.IsAccoutCorrect)
				{
					AppEnvironment.Settings.RefreshPostParameters();
					stateMachine.SetState(stateMachine.UnloginS);
				}

				OnGetLoginSourceCompleted();
			}
			else
			{
				//有可能在获取时已经手工导入了
				if (!AppEnvironment.Settings.IsLoginSourceCorrect)
				{
					lsg.GetLoginSourceAsync();
				}
			}
		}
	}
}
